import React, { useImperativeHandle, useRef } from 'react';
import { Form } from 'antd';
import { useControllableValue } from '@/hooks';
import { useUpdateEffect } from 'react-use';
import DynamicTable from './DynamicTable';

/**
 * 基础模板
 * @param props
 * @returns {JSX.Element}
 * @constructor
 */
const DynamicTableForm = React.forwardRef((props, ref) => {
    const { form, fieldName = 'param' } = props;
    const [value, onChange] = useControllableValue(props);
    const dynamicTableRef = useRef();
    const prevFormValuesRef = useRef();

    // 监听 list 变化
    useUpdateEffect(() => {
        const formValues = form.getFieldsValue();
        if (JSON.stringify(formValues[fieldName]) !== JSON.stringify(prevFormValuesRef.current)) {
            onChange(dynamicTableRef.current.methods.sortForm(formValues[fieldName]));
            prevFormValuesRef.current = formValues[fieldName];
        }
    }, [form]);

    // 暴露方法
    useImperativeHandle(ref, () => ({ value }));

    return (
        <Form layout="inline">
            <DynamicTable ref={dynamicTableRef} fieldName={fieldName} {...props} />
        </Form>
    );
});

DynamicTableForm.displayName = 'DynamicTableForm';

export default React.memo(Form.create()(DynamicTableForm));
